package com.whk.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.whk.pojo.Result;
import com.whk.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//在获取资源前执行该方法返回ture方行，false不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求的url
        //2.获取请求头中的token令牌
        String token = request.getHeader("token");
        log.info("获得令牌{}",token);

        //判断令牌是否存在
        if (token == null){
            //令牌不存在
            log.info("令牌不存在！");

            //创建响应结果对象
            Result responseResult = Result.error("NOT_LOGIN");
            //把Result对象转换为joson格式返回给前端
            String json = JSONObject.toJSONString(responseResult);//fastjson是专门实现对象和json的转换工具类
            //设置响应头,告诉浏览器相应的数据类型为json格式，响应的数据编码为UTF-8
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

            return false;//不放行
        }
        //解析token,如果解析失败，则表示未登录
        try {
            JwtUtils.parseJWT(token);
        }
        catch (Exception e){
            log.info("令牌解析失败!");
            //创建响应结果对象
            Result responseResult = Result.error("NOT_LOGIN");
            //把Result对象转换为joson格式返回给前端
            String json = JSONObject.toJSONString(responseResult);//fastjson是专门实现对象和json的转换工具类
            //设置响应头,告诉浏览器相应的数据类型为json格式，响应的数据编码为UTF-8
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

            return false;//不放行
        }

        return true;//放行
    }

    @Override//在获取资源后执行该方法ture放行，false不放行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("获取资源后执行！！");
    }

    @Override//视图渲染完毕后自动执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("页面渲染完执行！！");
    }
}
